package datastructure.sparsematrix;


/**
 * @author cyt
 * @create 2020-08-29 10:07
 */
public class SparseArray {


    public static void main(String[] args) {
        int[][] array = new int[11][11];
        /**
         * 原始的二维数组 -> 稀疏数组
         */
        array[1][2] = 1;
        array[2][3] = 2;
        printArray(array);

        System.out.println(getNoZero(array));
        int[][] ints = buildSparseArray(getNoZero(array), array);

        printArray(ints);
        int[][] buildArray = buildArray(ints);

        System.out.println();
        printArray(buildArray);
    }

    /**
     * 得到非零的元素个数
     *
     * @param array
     * @return
     */
    public static int getNoZero(int[][] array) {
        int sum = 0;
        /**
         * 原始的二维数组 -> 稀疏数组
         */
        for (int[] arr : array) {
            for (int item : arr) {
                if (item != 0) {
                    sum++;
                }
            }
        }
        return sum;
    }

    public static int[][] buildArray(int[][] array) {
        int[][] ints = new int[array[0][0]][array[0][1]];

        for (int i = 1; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                ints[array[i][0]][array[i][1]] = array[i][2];
            }
        }

        return ints;
    }

    /**
     * 创建稀疏数组
     *
     * @param sum
     * @return
     */
    public static int[][] buildSparseArray(int sum, int[][] array) {
        int[][] ints = new int[sum + 1][3];
        ints[0][0] = 11;
        ints[0][1] = 11;
        ints[0][2] = sum;
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) {
                if (array[i][j] != 0) {
                    count++;
                    ints[count][0] = i;
                    ints[count][1] = j;
                    ints[count][2] = array[i][j];
                }
            }
        }
        return ints;
    }


    /**
     * 打印二维数组
     *
     * @param ans
     */
    public static void printArray(int[][] ans) {
        for (int[] anInt : ans) {
            for (int i : anInt) {
                System.out.printf("%d ", i);
            }
            System.out.println();
        }
    }
}
